package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class TaoHuaService {

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;


    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;




    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private VideoMQService videoMQService;

    public Object saveVoice(MultipartFile videoFile) {
        Long userId = UserThreadLocal.get();

        Video video = new Video();
        video.setUserId(userId);
        try {
            //上传小视频
            String fileExtName = StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true);
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), fileExtName, null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        } catch (Exception e) {
            log.error("上传视频文件失败，userId = {}, file = {}", userId, videoFile.getOriginalFilename(), e);
            return ErrorResult.builder().errCode("501")
                    .errMessage("上传视频文件失败，请重试！").build();
        }

        String videoId = this.videoApi.saveVideo(video);

        //发消息
        this.videoMQService.videoMsg(videoId);
        if (StrUtil.isEmpty(videoId)) {
            return ErrorResult.builder().errCode("502")
                    .errMessage("保存语音数据失败，请重试！").build();
        }

        return null;
    }
}
